package com.aleaho.cftrack.presenter;

import android.util.Log;

import com.aleaho.cftrack.CFTrackApplication;
import com.aleaho.cftrack.http.ApiResponseWraperNoList;
import com.aleaho.cftrack.http.NetWorkUtil;
import com.aleaho.cftrack.http.entity.LoginEntity;
import com.aleaho.cftrack.utils.Constants;
import com.aleaho.cftrack.view.LoginView;

import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by Administrator on 2017/9/20.
 */

public class LoginPresenter {

    private LoginView loginView = null;
    private CFTrackApplication app = null;

    public LoginPresenter(LoginView loginView, CFTrackApplication application) {
        this.loginView = loginView;
        this.app = application;
    }


    public void login(String username, String password) {
        //        NetWorkUtil.
        NetWorkUtil.getLoginApi().login(username, password)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new Observer<ApiResponseWraperNoList<LoginEntity>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e(Constants.TAG, e.getMessage());
                        // Toast.makeText(LoginActivity.this, "登录出错！", Toast.LENGTH_SHORT).show();

                        loginView.loginError(e.getMessage());

                    }

                    @Override
                    public void onNext(ApiResponseWraperNoList<LoginEntity> xwEntity) {

                        if (xwEntity.getCode() == -100) {

                            loginView.loginError(xwEntity.getMsg());


                        } else {
                            LoginEntity loginEntity = xwEntity.getData();

                            app.setLoginEntity(loginEntity, true);
                            loginView.turnToMain();
                        }
                    }
                });

    }

}
